package com.tcsl.mylibrary.utils;


import android.util.Log;

import com.google.gson.Gson;
import com.wangpos.by.cashier3.CashierHelper;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.tcsl.canyin7.BuildConfig;
import cn.com.tcsl.canyin7.TCSLApplication;
import cn.com.tcsl.canyin7.bean.BpErrorInfo;
import cn.com.tcsl.canyin7.pay.OnPayListener;
import cn.weipass.pos.sdk.BizServiceInvoker;
import cn.weipass.service.bizInvoke.RequestInvoke;
import cn.weipass.service.bizInvoke.RequestResult;


/**
 * 旺pos结算时的帮助类
 * Created by wjx on 2016/11/18.
 */

public class WPPayUtil {
    private static final String TAG = "WPPayUtil";
    /**
     * bp业务的id
     */
    public static final String InvokeCashier_BPID = "57034f2afa0bab69c004fc36";
    /**
     * 开发者对应的ｋｅｙ值
     */
    public static final String InvokeCashier_KEY = "LYTiOo5igDDoQ7A66zEdhkf8TOcuY10e";

    private static final String Tag = "CashierSign";

    private static final String SignType = "MD5";
    private static final String inputCharset = "UTF-8";

    /**
     * 删除之前的结算接口
     *
     * @param wpwizServiceInvoker
     * @param cleanListener
     */
    public static void clean(BizServiceInvoker wpwizServiceInvoker, String pkName, BizServiceInvoker.OnResponseListener cleanListener) throws UnsupportedEncodingException {
        wpwizServiceInvoker.setOnResponseListener(cleanListener);
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("action", "clear_all_out_orders");
        JSONObject json = new JSONObject(dataMap);
        RequestInvoke cashierReq = new RequestInvoke();
        cashierReq.pkgName = pkName;
        cashierReq.sdCode = "CASH002";
        cashierReq.bpId = InvokeCashier_BPID;
        cashierReq.params = json.toString().getBytes("UTF-8");//{"action":"clear_all_out_orders"}
        cashierReq.params = json.toString().getBytes("UTF-8");
        RequestResult request = wpwizServiceInvoker.request(cashierReq);
        Log.i(TAG, request.token + "," + request.seqNo + "," + request.result);
    }

    /**
     * 请求刷卡消费
     *
     * @param wpwizServiceInvoker
     * @param mOnResponseListener 回调
     * @param mNeedPay            刷卡金额,以元为单位
     * @param pkName              包名
     * @param classname           文件名，刷卡完成后的返回位置而且调用此方法的类要设置 android:exported="true"
     *                            android:launchMode="singleTop"  两个属性
     * @param mBSID               订单号
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static void consume(BizServiceInvoker wpwizServiceInvoker, BizServiceInvoker.OnResponseListener mOnResponseListener, Float mNeedPay, String pkName, String classname, String mBSID) throws Exception {
        String tradeNo = new SimpleDateFormat("HHmmss").format(new Date());
        wpwizServiceInvoker.setOnResponseListener(mOnResponseListener);
        RequestInvoke cashierReq = new RequestInvoke();
        cashierReq.pkgName = pkName;
        cashierReq.sdCode = "CASH002";// 收银服务的sdcode信息
        cashierReq.bpId = InvokeCashier_BPID;
        String money = String.valueOf(Math.round(Double.valueOf(mNeedPay) * 100));
        Log.i(TAG, "wangPos pay:" + money);
        cashierReq.launchType = 1;
        cashierReq.params = sign(mBSID + tradeNo, money, pkName, classname);
        cashierReq.seqNo = "1";
        RequestResult request = wpwizServiceInvoker.request(cashierReq);
        Log.i(TAG, request.token + "," + request.seqNo + "," + request.result);
    }


    /**
     * 生成请求数据
     *
     * @param outTradeNo 订单号
     * @param totalFee   订单总金额，以分为单位
     * @param pkName     包名
     * @param name       调用该接口的类名，返回时，需要使用。而且调用此方法的类要设置 android:exported="true"
     *                   android:launchMode="singleTop"  两个属性
     * @return
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static byte[] sign(String outTradeNo, String totalFee, String pkName, String name) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("bp_id", InvokeCashier_BPID);
        dataMap.put("channel", "POS");   //交易渠道 固定“POS”
        dataMap.put("payType", "1006");  //支付方式  1006：银行卡
        dataMap.put("out_trade_no", outTradeNo);
        dataMap.put("body", "天财商龙拉卡拉手机点餐");  //订单描述
        dataMap.put("attach", "attach");
        dataMap.put("fee_type", "1");
        dataMap.put("total_fee", totalFee);
        dataMap.put("input_charset", inputCharset);
        dataMap.put("notify_url", "http://apps.weipass.cn/pay/notify");
        dataMap.put("classpath", name);
        dataMap.put("package", pkName);
        String sign = getSign(InvokeCashier_KEY, dataMap);
        dataMap.put("sign", sign);
        JSONObject json = new JSONObject(dataMap);
        return json.toString().getBytes(inputCharset);
    }

    /**
     * 加密
     *
     * @param invokeCashierKey
     * @param dataMap
     * @return
     */
    private static String getSign(String invokeCashierKey, Map<String, String> dataMap) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        List<String> keyList = new ArrayList<String>(dataMap.keySet());
        Collections.sort(keyList);
        StringBuilder builder = new StringBuilder();
        for (String mapKey : keyList) {
            builder.append(mapKey).append("=").append(dataMap.get(mapKey)).append("&");
        }
        builder.append("key=").append(invokeCashierKey);
        Log.i(TAG, "MD5加密前-->" + builder);
        MessageDigest md5 = MessageDigest.getInstance(SignType);
        md5.update(builder.toString().getBytes(inputCharset));
        byte[] md5Bytes = md5.digest();
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        Log.i(TAG, "MD5加密后-->" + hexValue);
        return hexValue.toString();
    }

    /**
     * 请求刷卡消费
     *
     * @param mListener
     * @param mNeedPay  刷卡金额,以元为单位
     * @param classname 文件名，刷卡完成后的返回位置而且调用此方法的类要设置 android:exported="true"
     *                  android:launchMode="singleTop"  两个属性
     * @param mBSID     订单号     @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static void miniconsume(final OnPayListener mListener, Float mNeedPay, String classname, String mBSID) throws Exception {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("out_trade_no", mBSID + System.currentTimeMillis());
        params.put("app_id", BuildConfig.BP_APP_ID);
        params.put("notify_url", "http://192.168.0.1/test");
        params.put("pay_type", "1");//类型，只使用银行卡，固定为1
        params.put("attach", "Here is the attach information.");
        String money = String.valueOf(Math.round(Double.valueOf(mNeedPay) * 100));
        params.put("total_fee", money);
        params.put("activity_path", classname);
        CashierHelper.consume(TCSLApplication.getInstance(), params, new CashierHelper.PayCallBack() {
            @Override
            public void success(final String data) {
                mListener.paySuccess("旺POS支付成功", "");
                //回调默认是在当前应用程序的主线程
                Log.d(TAG, "success: " + data);
            }

            @Override
            public void failed(String s) {
                Gson gson = new Gson();
                BpErrorInfo bpErrorInfo = gson.fromJson(s, BpErrorInfo.class);
                mListener.payError(bpErrorInfo.getErrMsg());
            }
        });
    }
}
